package io.fredia.femicro.gate.server.config;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import io.fredia.femicro.auth.client.config.UserAuthConfig;
import io.fredia.femicro.auth.client.jwt.UserAuthUtil;
import io.fredia.femicro.auth.common.util.jwt.IJWTInfo;
import io.fredia.femicro.gate.ratelimit.config.IUserPrincipal;

/**
 * 
 * 用户领域实现类
 * @author : Fredia
 * @since : 2018年3月13日
 * @version : v1.0.0
 */
public class UserPrincipal implements IUserPrincipal {

	@Autowired
	private UserAuthConfig userAuthConfig;
	@Autowired
	private UserAuthUtil userAuthUtil;

	@Override
	public String getName(HttpServletRequest request) {
		IJWTInfo infoFromToken = getJwtInfo(request);
		return infoFromToken == null ? null : infoFromToken.getUniqueName();
	}

	private IJWTInfo getJwtInfo(HttpServletRequest request) {
		IJWTInfo infoFromToken = null;
		try {
			String authToken = request.getHeader(userAuthConfig.getTokenHeader());
			if (StringUtils.isEmpty(authToken)) {
				infoFromToken = null;
			} else {
				infoFromToken = userAuthUtil.getInfoFromToken(authToken);
			}
		} catch (Exception e) {
			infoFromToken = null;
		}
		return infoFromToken;
	}

}
